package org.jeecg.modules.iot.bind.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.entity.ContentType;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.ChechDataAuthException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.app.v1.util.Const;
import org.jeecg.modules.iot.aio.Aio;
import org.jeecg.modules.iot.aio.AioConfiguration;
import org.jeecg.modules.iot.aio.ChannelContext;
import org.jeecg.modules.iot.aio.message.CheckMessage;
import org.jeecg.modules.iot.bind.entity.YlBindUser;
import org.jeecg.modules.iot.bind.service.IYlBindUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;
import org.jeecg.modules.iot.common.IotConst;
import org.jeecg.modules.iot.message.ReceivePopupIndex;
import org.jeecg.modules.iot.message.ReceivePopupSN;
import org.jeecg.modules.iot.message.ReceiveUpload;
import org.jeecg.modules.iot.serialport.SerialPortException;
import org.jeecg.modules.iot.tools.HttpServletUtils;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.iot.util.IotClientUtil;
import org.jeecg.modules.iot.util.QRCodeGenerator;
import org.jeecg.modules.power.device.entity.YlDevice;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.iot.tools.ByteUtils;
 /**
 * @Description: 设备绑定操作员表
 * @Author: jeecg-boot
 * @Date:   2024-09-03
 * @Version: V1.0
 */
@Api(tags="设备绑定操作员表")
@RestController
@RequestMapping("/api/bind")
@Slf4j
@RequiredArgsConstructor
public class YlBindUserController extends JeecgController<YlBindUser, IYlBindUserService> {

	private final IYlBindUserService ylBindUserService;

	private final IotClientUtil iotClientUtil;


	 @ApiOperation("登录接口")
	 @RequestMapping(value = "/login", method = RequestMethod.POST)
	 public Result<?> login(String userName,String password){

		 Result<JSONObject> result = new Result<JSONObject>();
		 QueryWrapper<YlBindUser> userQueryWrapper = new QueryWrapper<>();
		 userQueryWrapper.eq("user_name",userName).last("limit 1");
		 YlBindUser user = ylBindUserService.getOne(userQueryWrapper);
		 if(oConvertUtils.isEmpty(user))return Result.error_599("用户不存在");
		 //2. 校验用户名或密码是否正确
		 String userpassword = PasswordUtil.encrypt(userName, password, user.getSalt());
		 String syspassword = user.getUserPassword();
		 if (!syspassword.equals(userpassword)) return Result.error_599("用户名或密码错误");
		 return ylBindUserService.accountLogin(user);
	 }

	 @ApiOperation("绑定柜机")
	 @RequestMapping(value = "/bind", method = RequestMethod.POST)
	 public Result<?> bind(String url,String rentBoxSn,HttpServletRequest request){
		 YlBindUser user = ylBindUserService.getUserByToken(request);
		 if(oConvertUtils.isEmpty(rentBoxSn))return Result.error_599("缺少关键参数rentBoxSn");
		 /**
		  * 通过url拿到id
		  */
		 Map<String, Object> map = HttpServletUtils.getParams(url);
		 Object qrcodeID = map.get("id");
		 if(oConvertUtils.isEmpty(qrcodeID))return Result.error_599("URL中缺少关键参数id");
		 String id = qrcodeID.toString();
		 ylBindUserService.bindDevice(id,rentBoxSn);
		 return Result.ok("绑定成功");
	 }

	 @ApiOperation("解绑柜机")
	 @RequestMapping(value = "/unbind", method = RequestMethod.POST)
	 public Result<?> unbind(String url,String rentBoxSn,HttpServletRequest request){
		 YlBindUser user = ylBindUserService.getUserByToken(request);
		 /**
		  * 通过url拿到id
		  */
		 Map<String, Object> map = HttpServletUtils.getParams(url);
		 Object qrcodeID = map.get("id");
		 if(oConvertUtils.isEmpty(qrcodeID))return Result.error_599("缺少关键参数id");
		 String id = qrcodeID.toString();
		 ylBindUserService.unbindDevice(id,rentBoxSn);
		 return Result.ok("绑定成功");
	 }

	 @ApiOperation("扫码测试")
	 @RequestMapping(value = "/testDevice", method = RequestMethod.POST)
	 public Result<?> testDevice(String url,HttpServletRequest request){
		 YlBindUser user = ylBindUserService.getUserByToken(request);
		 /**
		  * 通过url拿到id
		  */
		 Map<String, Object> map = HttpServletUtils.getParams(url);
		 Object qrcodeID = map.get("id");
		 if(oConvertUtils.isEmpty(qrcodeID))return Result.error_599("缺少关键参数id");
		 String id = qrcodeID.toString();
		 JSONObject jsonObject  = ylBindUserService.queryDevice(id);
		 if(oConvertUtils.isEmpty(jsonObject))return Result.error_599("数据错误，暂未查询到相关的设备信息");
		 return Result.ok(jsonObject);
	 }

	 @ApiOperation("扫码测试1")
	 @RequestMapping(value = "/testDevice1", method = RequestMethod.POST)
	 public Result<?> testDevice1(String url,HttpServletRequest request) throws SerialPortException {
		 YlBindUser user = ylBindUserService.getUserByToken(request);
		 /**
		  * 通过url拿到id
		  */
		 Map<String, Object> map = HttpServletUtils.getParams(url);
		 Object qrcodeID = map.get("id");
		 if(oConvertUtils.isEmpty(qrcodeID))return Result.error_599("缺少关键参数id");
		 String id = qrcodeID.toString();

		 String data = "A8 00 C5 10 10 00 00 00 0D 01 01 00 00 00 00 00 00 00 00 FF FF FF FF 00 00 02 00 00 00 00 00 00 00 00 FF FF FF FF 00 00 03 00 00 00 00 00 00 00 00 FF FF FF FF 00 00 04 00 00 00 00 00 00 00 00 FF FF FF FF 00 00 05 00 00 00 04 00 00 00 00 FF FF FF FF 00 00 06 01 00 00 04 00 98 98 19 64 1A 32 00 01 01 60 00 00 00 0D 01 1F 00 00 00 00 00 00 00 00 FF FF FF FF 00 00 20 00 00 00 00 00 00 00 00 FF FF FF FF 00 00 21 00 00 00 00 00 00 00 00 FF FF FF FF 00 00 22 00 00 00 04 00 00 00 00 FF FF FF FF 00 00 23 00 00 00 04 00 00 00 00 FF FF FF FF 00 00 24 00 00 00 04 00 00 00 00 FF FF FF FF 00 00 35";
		 byte[] bytes = ByteUtils.toBytes(data);
		 ReceiveUpload receiveUpload = new ReceiveUpload(bytes);
//		 ReceiveUpload receiveUpload = ylBindUserService.queryDevice(id);
		 if(oConvertUtils.isEmpty(receiveUpload))return Result.error_599("数据错误，暂未查询到相关的设备信息");
		 JSONObject jsonObject = ylBindUserService.jsonEntity(receiveUpload,"testDeviceSn");
		 return Result.ok(jsonObject);
	 }

	 @ApiOperation("SN弹出")
	 @RequestMapping(value = "/popupSn", method = RequestMethod.POST)
	 public Result<?> popupSn(String deviceSn,String sn,HttpServletRequest request){
		 YlBindUser user = ylBindUserService.getUserByToken(request);
		 ReceivePopupSN receivePopupSN = ylBindUserService.popupSn(deviceSn,sn);
		 if(receivePopupSN.getStatus() != 0x01){
			 throw new ChechDataAuthException("Popup Error:" + ByteUtils.to16Hexs(receivePopupSN.getBytes()));
		 }
		 return Result.ok(receivePopupSN.getSnAsString());
	 }

	 @ApiOperation("孔位弹出")
	 @RequestMapping(value = "/popupHole", method = RequestMethod.POST)
	 public Result<?> popupHole(String deviceSn,String hole,String io,HttpServletRequest request){
		 YlBindUser user = ylBindUserService.getUserByToken(request);
		 ReceivePopupIndex popupIndex = ylBindUserService.popupHole(deviceSn,hole,io);
		 if(popupIndex.getStatus() != 0x01){
			 throw new ChechDataAuthException("Popup Error:" + ByteUtils.to16Hexs(popupIndex.getBytes()));
		 }
		 return Result.ok(popupIndex.getStatus());
	 }

	 /**
	  *
	  * @return
	  */
	 @ApiOperation("获取设备类型")
	 @RequestMapping(value = "/category", method = RequestMethod.POST)
	 public Result<?>  getCategory(){
		 return Result.ok(ylBindUserService.getCategory());
	 }

	 /**
	  *
	  * @param id 生成二维码对应设备的类型，关联设备类型获取轮巡充数量
	  * @return
	  */
	 @ApiOperation("生成二维码")
	 @RequestMapping(value = "/qrcode", method = RequestMethod.POST)
	 public Result<?> getQrCode(String id) throws IOException {
		 YlDevice device = ylBindUserService.getQrCodeId(id);
		 return Result.ok(device);
	 }

	 /**
	  *
	  * @param id 生成二维码对应设备的类型，关联设备类型获取轮巡充数量
	  * @return
	  */
	 @ApiOperation("删除未使用的二维码")
	 @RequestMapping(value = "/delQrcode", method = RequestMethod.POST)
	 public Result<?> delQrcode(String id) throws IOException {
		 ylBindUserService.deleteDevice(id);
		 return Result.ok("已删除");
	 }

	 /**
	  *
	  * @param id 生成二维码对应设备的类型，关联设备类型获取轮巡充数量
	  * @return
	  */
	 @ApiOperation("发送指令消息")
	 @RequestMapping(value = "/sendMsg", method = RequestMethod.POST)
	 public Result<?> sendMsg(String id) {
		 ylBindUserService.sendMsg(id);
		 return Result.ok("已删除");
	 }

	 /**
	  * @param sn 设备IMEI码
	  * @return
	  */
	 @ApiOperation("获取设备信息")
	 @RequestMapping(value = "/getDevice", method = RequestMethod.POST)
	 public Result<?> getDevice(String sn){
		 AioConfiguration configuration = Aio.getAioConfiguration(iotClientUtil.getProductKey());
		 ChannelContext channelContext = configuration.queueList.getChannelContext(sn,configuration);
		 ReceiveUpload receiveUpload = channelContext.getReceiveUpload();
		 return Result.OK(receiveUpload);
	 }

//	 @ApiOperation("二维码请求URL")
//	 @RequestMapping(value = "/get", method = RequestMethod.POST)
//	 public Result<?> get(String id){
//
//		 return Result.ok();
//	 }



}
